package com.course.filter;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.course.component.constant.CacheConstants;
import com.course.component.util.TokenUtil;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;

@Component
public class SystemRouterGatewayFilter implements GatewayFilter, Ordered {

    @Resource
    RedisTemplate redisTemplate;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //路由中的过滤器 filter
        String path = exchange.getRequest().getURI().getPath();
        //不需要登陆直接返回
        if(!path.contains("/system")){
            return chain.filter(exchange);
        }

        //不需要登陆直接返回
        if(!path.contains("/master/x/login")){
            return chain.filter(exchange);
        }

        String token = exchange.getRequest().getHeaders().getFirst("Authorization");
        if(StringUtils.isNotEmpty(token) && token.startsWith("Bearer ")){
            token = token.replaceFirst("Bearer ", "");
        }
        if (StringUtils.isBlank(token)) {
            token = exchange.getRequest().getQueryParams().getFirst("token");
        }
        if(token == null || token.isEmpty()){
            //为空时拦截
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }

        //单点登陆实现
        //可以通过REDIS获取用户信息
        Object object = null;
        try {
            object = redisTemplate.opsForValue().get(getTokenKey(TokenUtil.getAudience(token)));
        } catch (Exception e) {
            String message = "{\"status\": 401,\"message\": \"Unauthorized Request!Token 已经过期\"}";
            return responseSelf(exchange,message);
        }
        if(object == null){
            String message = "{\"status\": 401,\"message\": \"Unauthorized Request!Token 已经过期\"}";
            return responseSelf(exchange,message);
        }
        /*
        //通过用户信息获取用户权限。并判断路由是否授权
        .....
        */
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    //可以自定义枚举，或者将返回添加到配置中
    private Mono<Void> responseSelf(ServerWebExchange exchange,String message){
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        byte[] bytes = message.getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bytes);
        // 设置编码utf-8，否则浏览器中文可能会乱码
        response.getHeaders().add("content-type", "text/plain;charset=utf-8");
        return response.writeWith(Flux.just(buffer));
    }

    private String getTokenKey(String token) {
        return CacheConstants.LOGIN_TOKEN_KEY + token;
    }

}
